package com.taikang.system.task;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.taikang.system.dao.ISysEmailDao;
import com.taikang.system.entity.SysEmail;
import com.taikang.system.entity.SysEmailServerConfig;
import com.taikang.system.service.ISysEmailServerConfigService;

/**
 * 邮件发送定时器
 * @creator     taikang
 * @create-time 2016年5月9日   下午5:44:20
 * @email taikang@taikang.com
 * @company www.taikang.com
 * @version 1.0
 */
@Component
public class SysMailSendTask {
	
	private Log logger = LogFactory.getLog(SysMailSendTask.class);
	
	@Autowired
	private ISysEmailDao sysEmailDao;
	@Autowired
	private ISysEmailServerConfigService configService;

	/**
	 * 发送邮件每10秒执行一次
	 * @throws Exception
	 */
	@Scheduled(cron = "0/10 * * * * ?")
	public void sendMailTask()throws Exception{
		logger.debug("发送邮件");
		// 取出未发送邮件列表
		List<SysEmail> sysEmailList = sysEmailDao.listTenNoSendMail();
		if(CollectionUtils.isEmpty(sysEmailList)){
			return;
		}
		
		//设置发送参数
		Properties props = new Properties();
		props.put("mail.debug", "false");
		props.put("mail.smtp.auth", "true");
		Session s = Session.getInstance(props);
		
		MimeMessage message = new MimeMessage(s); 
		SysEmailServerConfig config = configService.getEmailServerConfig();
		
		String hostName = config.getHostName();	//邮箱服务器
		String account = config.getAccount();	//账号
		String password = config.getPassword();	//密码
		String fromName = config.getFromName();	//发件人
		
		// 设置发件人名称
		try {
			String nick = javax.mail.internet.MimeUtility.encodeText(fromName);
			message.setFrom(new InternetAddress(nick + " <" + account + ">"));
		} catch (UnsupportedEncodingException e) {
			logger.error("",e);
			message.setFrom(new InternetAddress(account));
		}
		
		Transport transport = null;
        try{
        	transport = s.getTransport("smtp");  
            transport.connect(hostName, account, password); 
            
            for (SysEmail sysEmail : sysEmailList) {
            	try{
            		//设置邮件信息
            		message.setSubject(sysEmail.getTitle());
    	        	BodyPart mdp = new MimeBodyPart();  
    		        mdp.setContent(sysEmail.getContent(),"text/html;charset=utf-8");  
    		        Multipart mm = new MimeMultipart();
    		        mm.addBodyPart(mdp); 
    		        message.setContent(mm);
    		        //设置接收人
    				String toEmail = sysEmail.getEmail();
    				if(StringUtils.isNotBlank(toEmail)){
    					String[] to = toEmail.split(";");
    					InternetAddress[] toAddress = new InternetAddress[to.length];  
    			        for (int i = 0; i < to.length; i++){
    			        	toAddress[i] = new InternetAddress(to[i]);
    			        }
    			        message.setRecipients(Message.RecipientType.TO, toAddress);  
    				}
    				message.setSentDate(new Date()); 
    				message.saveChanges();
    				
    				//开始发送
    		        transport.sendMessage(message, message.getAllRecipients());  
    				
    		        //更新邮件状态，1-发送成功
    				sysEmailDao.updateEmailState(sysEmail.getId(), 1);
            	}catch(Exception ex){
            		String msg = "发送邮件时发生异常：" + ex.getMessage();
            		logger.error(msg,ex);
            		
            		//更新邮件状态，2-发送失败
    				sysEmailDao.updateEmailState(sysEmail.getId(), 2);
            	}
    		}
            
        }catch(Exception ex){
        	logger.error("",ex);
        }finally{
        	if(null != transport){
        		transport.close();
        	}
        }
		
	}
}
